/*
 * =====================================================================================
 *
 *       Filename:  observable.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  10/03/2010 02:56:58 AM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Ken Chen (Ziliang), zlchen.ken@gmail.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#include <algorithm>
#include <functional>
#include "observable.h"
#include "observer.h"

using namespace std;

template<typename T>
struct Deleter: public unary_function<T, void>
{
  void operator()( T& t ) const
	{
	  delete t;
	}
};

template<typename T1, typename T2>
struct Updater: public binary_function<T1, T2, void>
{
  void operator()( T1& t1, T2& t2 ) const
	{
	  t1->update( t2 );
	}
};

Observable::Observable()
	: itsObservers()
{
}

Observable::~Observable()
{
  for_each( itsObservers.begin(), itsObservers.end(), Deleter<Observer*>() );
}

void Observable::addObserver( Observer* o )
{
  itsObservers.push_back( o );
}

void Observable::removeObserver( const Observer* o )
{
  remove( itsObservers.begin(), itsObserver.end(), o );
}

void Observable::notifyObservers( void )
{
  for_each( itsObservers.begin(), itsObservers.end(), 
			                        bind2nd( Updater<Observer*, Observable*>(), this ) );
}

